package com.pudutech.bluetoothdemo.bluetooth

import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothServerSocket
import android.bluetooth.BluetoothSocket
import android.content.Context
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.io.IOException
import java.io.InputStream

class ServerSocket {
    private var context: Context? = null
    private var currentDevice: BluetoothDevice? = null
    private var mReadListener: ReadListener? = null
    private var mServerSocket: BluetoothServerSocket? = null
    private var mSocket: BluetoothSocket? = null
    private var serverName = "defServerName"

    constructor(context: Context, currentDevice: BluetoothDevice?, mReadListener: ReadListener?) {
        this.context = context
        this.currentDevice = currentDevice
        this.mReadListener = mReadListener
        init()
    }

    private fun init() {
        mServerSocket = BluetoothUtils.getBluetoothAdapter(context!!)
            .listenUsingRfcommWithServiceRecord(serverName, BluetoothUtils.getUUID())
        GlobalScope.launch {
            var input: InputStream? = null
            try {
                val buffer = ByteArray(1024)
                while (true) {
                    //在服务器端调用方法accept()监听，当有客户端请求到来时,accept()方法返回BluetoothSocket，通过InputStream和OutputStream来实现数据的传输。
                    mSocket = mServerSocket?.accept()
                    input = (mSocket as BluetoothSocket).inputStream
                    var bytes = input.read(buffer)
                    if (bytes > 0) {
                        val buf_data = ByteArray(bytes)
                        for (i in 0..bytes - 1) {
                            buf_data[i] = buffer[i]
                        }
                        val s = String(buf_data)
                        //处理蓝牙通信读取到的  内容
                        mReadListener?.readMessage(s)
                    }
                }
            } catch (e1: IOException) {
                e1.printStackTrace()
            } finally {
                try {
                    if (input != null) {
                        input.close()
                    }
                } catch (e1: IOException) {
                    e1.printStackTrace()
                }
            }
        }
    }

    fun close() {
        mSocket?.close()
        mServerSocket?.close()
    }
}